<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="160px" class="productForm">
    <el-row>
      <el-col :span="10">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="10">
        <el-form-item label="原价" prop="originPrice">
          <el-input v-model="ruleForm.originPrice"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="10">
        <el-form-item label="现价" prop="presentPrice">
          <el-input v-model="ruleForm.presentPrice"></el-input>
        </el-form-item>
      </el-col>
     
    </el-row>

    <el-row>
      <el-col :span="10">
        <el-form-item label="团长佣金占比(%)" prop="proportion">
          <el-input v-model="ruleForm.proportion"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="10">
        <el-form-item label="库存" prop="stock">
          <el-input v-model="ruleForm.stock"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="4">
        <el-form-item label="是否限制购买">
          <el-switch v-model="ruleForm.isLimit" :active-value="open" :inactive-value="close" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>
      </el-col>
      <el-col :span="6" v-show="ruleForm.isLimit == 1">
        <el-form-item label="限购数量">
          <el-input v-model="ruleForm.limitBuy"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

     <el-row>
      <el-col :span="10">
        <el-form-item label="虚拟购买数量">
          <el-input v-model="ruleForm.mock"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- <el-row>
      <el-col :span="10">
        <el-form-item label="图片" prop="imgUrl">
          <el-upload class="avatar-uploader" action="/api/upload" 
          :show-file-list="false" :on-success="handleAvatarSuccess" 
          :headers="auth">
            <img v-if="ruleForm.imgUrl" :src="ruleForm.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row> -->

    <el-row>
      <el-col :span="22">
        <el-form-item label="图片">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess" 
            :file-list="fileList"
            :headers="auth">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>

        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <el-form-item label="描述" prop="description">
          <textarea rows="6" v-model="ruleForm.description"></textarea>
        </el-form-item>
      </el-col>
    
    </el-row>

    <el-form-item>
      <el-button type="primary" @click="handleSubmit">修 改/提 交</el-button>
      <el-button @click="goBack">返 回</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import api from "@/api/product";

const SUCCESS = 0;
export default {
  data() {
    return {
      auth: { token: this.$store.state.token },
      ruleForm: {
        id: null,
        name: "",
        imgName: "",
        imgUrl: "",
        originPrice: "",
        presentPrice: "",
        proportion: "",
        stock: "",
        description: "",
        isLimit: 0,
        limitBuy: "",
        mock: ""
      },
      rules: {
        name: [
          { required: true, message: "请填写商品名称", trigger: "change" }
        ],
        originPrice: [
          { required: true, message: "请填写商品原价", trigger: "change" }
        ],
        presentPrice: [
          { required: true, message: "请填写商品现价", trigger: "change" }
        ],
        proportion: [
          { required: true, message: "请填写团长佣金占比", trigger: "change" }
        ],
        stock: [
          { required: true, message: "请填写商品库存", trigger: "change" }
        ],
        description: [
          { required: true, message: "请填写商品描述", trigger: "change" }
        ]
      },
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      open: 1,
      close: 0
    };
  },
  created() {
    let id = this.$route.query.id;
    if (id) {
      this.ruleForm.id = id;
      this._getDetail();
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
      let index = this.fileList.indexOf(file);
      this.fileList.splice(index, 1);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file) {
      if (res.code == SUCCESS) {
        let newFile = {};
        newFile.name = res.data.fileName;
        newFile.url = res.data.fileUrl;
        this.fileList.push(newFile);
        console.log(this.fileList);
      }
    },
    _getDetail() {
      api.getDetail(this.ruleForm.id).then(response => {
        if (response.code == SUCCESS) {
          let product = response.data.product;
          let productStock = response.data.productStock;
          Object.assign(product, { stock: productStock.stock });
          this.ruleForm = product;

          let imgNameArray = this.ruleForm.imgName.split("#");
          let imgUrlArray = this.ruleForm.imgUrl.split("#");

          for (let i = 0; i < imgNameArray.length; i++) {
            let file = {};
            file.name = imgNameArray[i];
            file.url = imgUrlArray[i];
            this.fileList.push(file);
          }
        }
      });
    },
    handleSubmit() {
      this.ruleForm.name = this.ruleForm.name.trim();
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          //验证价格和数量
          const priceRegular = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
          const numberRegular = /^[1-9]\d*|0$/;

          //商品原价
          if (!priceRegular.test(this.ruleForm.originPrice)) {
            this.$message({
              type: "warning",
              message: "商品原价非法,请重新填写"
            });
            return;
          }

          //商品现价
          if (!priceRegular.test(this.ruleForm.presentPrice)) {
            this.$message({
              type: "warning",
              message: "商品现价非法,请重新填写"
            });
            return;
          }

          //团长佣金占比
          if (!numberRegular.test(this.ruleForm.proportion)) {
            this.$message({
              type: "warning",
              message: "团长佣金占比非法,请重新填写"
            });
            return;
          }

          if (this.ruleForm.proportion.toString().includes(".")) {
            this.$message({
              type: "warning",
              message: "团长佣金占比不能是小数类型,请重新填写"
            });
            return;
          }

          if (this.ruleForm.proportion > 100) {
            this.$message({
              type: "warning",
              message: "团长佣金占比不能大于100,请重新填写"
            });
            return;
          }

          //库存
          if (!numberRegular.test(this.ruleForm.stock)) {
            this.$message({
              type: "warning",
              message: "库存非法,请重新填写"
            });
            return;
          }

          this.addOrUpdate();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    addOrUpdate() {
      let imgNameArray = [];
      let imgUrlArray = [];

      this.fileList.forEach(element => {
        imgNameArray.push(element.name);
        imgUrlArray.push(element.url);
      });

      this.ruleForm.imgName = imgNameArray.join("#");
      this.ruleForm.imgUrl = imgUrlArray.join("#");
      if (this.ruleForm.id) {
        this._updateObj();
      } else {
        this._addObj();
      }
    },
    _addObj() {
      api.add(this.ruleForm).then(response => {
        if (response.code == SUCCESS) {
          this.$message({
            type: "success",
            message: "操作成功"
          });
          this.$router.push({ path: "/product/list" });
        } else {
          this.$message({
            type: "warning",
            message: response.message
          });
        }
      });
    },
    _updateObj() {
      api.update(this.ruleForm).then(response => {
        if (response.code == SUCCESS) {
          this.$message({
            type: "success",
            message: "操作成功"
          });
          this.$router.push({ path: "/product/list" });
        } else {
          this.$message({
            type: "warning",
            message: response.message
          });
        }
      });
    },
    goBack() {
      this.$router.back();
    }
  }
};
</script>


<style lang="less">
@import "./product-edit.less";
</style>